package sa.com.sure.ejtimaa.database;


import sa.com.sure.ejtimaa.common.AppHelper;
import sa.com.sure.ejtimaa.model.ReplyTypeInfo;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.SQLException;


public class ReplyTypes {

	private DataBaseHelper dbHelper;
	
	public static final String TABLE_Name = "ReplyTypes";
	
    public static final String ReplyTypeIDField = "ReplyTypeID"; 
    public static final String ReplyTypeNameField = "ReplyTypeName";
    
    private String[] allColumns = { ReplyTypeIDField, ReplyTypeNameField  };
    
    Cursor cursor = null;
    
    public ReplyTypes(Context context)  {
 		dbHelper = new DataBaseHelper(context);
 		dbHelper.createDataBase();
 	}
        
    public static ReplyTypes Instance = new ReplyTypes(AppHelper.getAppContext());
    
	public void open() throws SQLException {
		dbHelper.openDataBase();
	}
	
	public void close() {
		if(cursor!=null && !cursor.isClosed())
			cursor.close();
		dbHelper.close();
	}
	
	public void addItem(ReplyTypeInfo item) { 

		try
		{ 
			open();
			
	        ContentValues values = new ContentValues(); 
	        
	        values.put(ReplyTypeIDField, item.GetReplyTypeID()); 
	        values.put(ReplyTypeNameField, item.GetReplyTypeName()); 
	        
	        dbHelper.db.insert(TABLE_Name, null, values); 

		}
		finally{
			close();
		}
	
    } 
	
	
	public ReplyTypeInfo GetItem(int ReplyTypeID) throws SQLException{
		
		try{
		
			open();
		
			ReplyTypeInfo item = null;
			
			cursor = dbHelper.db.query(TABLE_Name,allColumns, ReplyTypeIDField + "=" + ReplyTypeID ,null,null,null,null);
	        if (cursor != null ) {
	        	cursor.moveToFirst();	
	        	if(cursor.getCount()>0)
	        		item =  getItemInfo(cursor);
	        	
	        }	        	        	       
	        
	    	return item;	        
		}
		finally{
			close();
		}
	}
	
	 public boolean updateItem(ReplyTypeInfo item) {

		 try
		 {
		 	open();
		 	
		    ContentValues args = new ContentValues();		    
		    args.put(ReplyTypeNameField, item.GetReplyTypeName());		    
		    boolean res =   dbHelper.db.update(TABLE_Name, args, ReplyTypeIDField + "=" + item.GetReplyTypeID() , null) > 0;		    
		    
		    return res;	    
		}
		finally{
			
			close();
		}
	 }
	
	
    private ReplyTypeInfo getItemInfo(Cursor cursor) {  
  
    	return new ReplyTypeInfo(cursor.getInt(0),cursor.getString(1));    	   
	}
}
